package com.ruoyi.common.filter

import com.ruoyi.common.enums.HttpMethod
import com.ruoyi.common.utils.MyStringUtils
import java.io.IOException
import javax.servlet.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 防止XSS攻击的过滤器
 *
 * @author ruoyi
 */
class XssFilter : Filter {
    /**
     * 排除链接
     */
    private var excludes: MutableList<String> = mutableListOf()
    @Throws(ServletException::class)
    override fun init(filterConfig: FilterConfig) {
        val tempExcludes: String = filterConfig.getInitParameter("excludes")
        if (MyStringUtils.isNotEmpty(tempExcludes)) {
            val url: Array<String> = tempExcludes.split(",").toTypedArray()
            var i = 0
            while (i < url.size) {
                excludes.add(url[i])
                i++
            }
        }
    }

    @Throws(IOException::class, ServletException::class)
    override fun doFilter(request: ServletRequest, response: ServletResponse?, chain: FilterChain) {
        val req: HttpServletRequest = request as HttpServletRequest
        val resp: HttpServletResponse? = response as HttpServletResponse?
        if (handleExcludeURL(req, resp)) {
            chain.doFilter(request, response)
            return
        }
        val xssRequest = XssHttpServletRequestWrapper(request)
        chain.doFilter(xssRequest, response)
    }

    private fun handleExcludeURL(request: HttpServletRequest, response: HttpServletResponse?): Boolean {
        val url: String = request.servletPath
        val method: String = request.method
        // GET DELETE 不过滤
        return if (HttpMethod.GET.matches(method) || HttpMethod.DELETE.matches(method)) {
            true
        } else MyStringUtils.matches(url, excludes)
    }

    override fun destroy() {
    }
}
